from base.tools.develop_tools import Singleton
from base.config.redis_config import RedisConfig
import redis
import pickle


class RedisServer(metaclass=Singleton):
    def __init__(self):
        self.pool = redis.ConnectionPool(
            host=RedisConfig.HOST,
            port=RedisConfig.PORT,
            db=RedisConfig.DBID,
            max_connections=100,
        )

    @property
    def conn(self):
        return redis.Redis(
            connection_pool=self.pool,
            decode_responses=True,
            socket_keepalive=True,
        )

    def write(self, key, value, expire=None):
        """
        写入键值对
        """
        # 判断是否有过期时间，没有就设置默认值
        if expire:
            expire_in_seconds = expire
        else:
            expire_in_seconds = RedisConfig.REDIS_EXPIRE
        with self.conn as conn:
            conn.set(key, pickle.dumps(value), ex=expire_in_seconds)

    def read(self, key):
        """
        读取键值对内容
        """
        with self.conn as conn:
            if conn.get(key):
                return pickle.loads(conn.get(key))
            else:
                return None
